<template>
	<view class="homeContainer">

		<view v-if="isExpires" class="expiresWrapper">
			临时服务器已到期，请续费
		</view>
		<template v-else>
			<view class="logoWrapper">
			</view>
			<view class="nameWrapper">
				梦维营销
			</view>
			<template v-if="isShowLogin">
				<view class="itemContainer">
					<view class="left">
						<image class="icon" src="@/static/image/icon_project.png" mode=""></image>
						<input v-model="projectId" @input="onProjectChange" class="inputWrapper" type="number"
							placeholder="输入项目编号" />
					</view>
					<view class="right">

					</view>
				</view>
				<view class="itemContainer">
					<view class="left">
						<image class="icon" src="@/static/image/icon_phone.png" mode=""></image>
						<input v-model="phoneNum" class="inputWrapper" type="number" placeholder="输入手机号" />
					</view>
					<view class="right">

					</view>

				</view>
				<view class="itemContainer">
					<view class="left">
						<image class="icon" src="@/static/image/icon_checkcode.png" mode=""></image>
						<input v-model="checkCode" class="inputWrapper"  type="number"
							placeholder="输入验证码" />
					</view>
					<template v-if="phoneNum&&phoneNum.length>9">
						<view v-if="cutdownNum>0" class="cutDownWrapper">
							<text class="text">{{cutdownNum}}</text>秒后重新发送
						</view>
						<view v-else class="sendCheckCodeWrapper" @click="onSendCheckCode">
							发送验证码
						</view>
					</template>

				</view>
				<view class="checkLoginBtnWrapper" @click="onCheckCodeLogin">
					登录
				</view>
				<view class="phoneLoginBtnWrapper" @click="onAuthLogin">
					本机号码 一键登录
				</view>
				<view class="phoneLoginBtnWrapper" style="background-color: #17f;color: #fff;" @click="onRegister">
					注册
				</view>
				<view class="bottomContainer">
					<view class="" style="display: flex;align-items: center;">
						<view class="checkBoxWrapper" @click="onChangeAgreement">
							<image v-if="isAgreement" src="@/static/image/icon_right.png"
								style="width: 100%;height: 100%;" mode=""></image>
						</view>
						<text style="color: #888888;">阅读并同意</text>
						<view @click="gotoAgreement(0)">《用户协议》</view>
						<text style="color: #888888;">和</text>
						<view @click="gotoAgreement(1)">《隐私协议》</view>
					</view>
				</view>
			</template>
		</template>
	</view>
</template>

<script>
	const api = require("@/static/js/api.js")
	import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'

	import {
		mapActions,
		mapMutations,
		mapState
	} from 'vuex';


	let that = null
	let timeId = null
	let App = getApp()
	export default {
		data() {
			return {
				shareObj: {
					sharePath: "",
				},
				firstLogin: true,
				isShowLogin: false,
				loginType: 0, //0 短信登录， 1 一键登录
				isAgreement: false,

				phoneNum: "",
				checkCode: "",
				projectId: "",
				cutdownNum: 0,

				navigateToUrl: '',
			};
		},
		components: {

		},
		computed: {
			...mapState({
				hasLogin: state => state.userInfo.hasLogin,
				isAuthPhone: state => state.userInfo.isAuthPhone,
				isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
				isSeller: state => state.userInfo.isSeller,
				sellerObj: state => state.userInfo.sellerObj,
				buyerObj: state => state.userInfo.buyerObj,
				shopInfo: state => state.userInfo.shopInfo,
				isExpires: state => state.userInfo.isExpires,
			}),
		},

		onLoad(options) {
			let _this = this
			that = this
			console.log("home onload:", options)
			let scene = ""
			if (options.scene) {
				scene = decodeURIComponent(options.scene)
			}
			if (uni.getStorageSync("projectId")) {
				that.projectId = uni.getStorageSync("projectId")
			}
			// #ifdef APP-PLUS
			checkUpdate().then(res=>{
				console.log("checkUpdate", res)
			}).catch(err=>{
				console.log("checkUpdate err", err)
			})
			// #endif

				
			that.initUserType();
			that.navigateToByScene(scene, options)

			// //  监听键盘高度变化
			// uni.onKeyboardHeightChange((obj) => {
			// 	_this.keyboardHeight = obj
			// 	if (obj.height > 0) {
			// 		_this.editorHeight = _this.Height - obj.height
			// 		setTimeout(() => {
			// 			_this.showKeyBoard = true
			// 		}, 100)
			// 	} else {
			// 		_this.editorHeight = _this.Height - uni.upx2px(110)
			// 		_this.showKeyBoard = false
			// 	}
			// 	console.log("editorHeight:", _this.editorHeight, _this.showKeyBoard)
			// })
		},
		onReady() {

		},
		onShow() {
			if (that.firstLogin) {
				that.firstLogin = false
			} else {
				if (that.hasLogin && !that.isExpires) {
					that.gotoPage()
				} else {
					that.getUserInfo()
				}
			}
		},
		onUnload() {

		},
		methods: {
			...mapMutations(['setUserInfo', 'setShopInfo', 'setLoginStatus', 'setUserId', "setOrigin", "setPreviewMode"]),

			onProjectChange() {
				uni.setStorageSync("projectId", that.projectId);
			},

			onChangeAgreement() {
				that.isAgreement = !that.isAgreement
			},

			onSendCheckCode() {
				api.getLoginAuthCode({
					phone: that.phoneNum
				}).then(res => {

				})
				clearInterval(timeId)
				that.cutdownNum = 60
				timeId = setInterval(() => {
					that.cutdownNum--;
					if (that.cutdownNum <= 0) {
						clearInterval(timeId)
					}
				}, 1000)
			},

			checkParam() {
				if (!that.isAgreement) {
					uni.showToast({
						icon: "none",
						title: '阅读并同意，《用户协议》和《隐私协议》'
					})
					return false
				}

				if (!(that.phoneNum && that.phoneNum.length == 11)) {
					uni.showToast({
						icon: "none",
						title: '请输入正确的手机号'
					})
					return false
				}

				if (!(that.checkCode && that.checkCode.length == 4)) {
					uni.showToast({
						icon: "none",
						title: '请输入验证码'
					})
					return false
				}

				if (!(that.projectId && that.projectId.length == 4)) {
					uni.showToast({
						icon: "none",
						title: '请输入项目编号'
					})
					return false
				}
				return true
			},

			checkProjectId() {
				if (!(that.projectId && that.projectId.length == 4)) {
					uni.showToast({
						icon: "none",
						title: '请输入项目编号'
					})
					return false
				}
				return true
			},

			gotoAgreement(id) {
				console.log("gotoAgreement", id)
				uni.navigateTo({
					url: '/pages/home/agreement?id=' + id
				})
			},



			setShareObj(obj) {
				//==== 1为预览模式  0为正常模式
				if (obj.preview == 1) {
					uni.setStorageSync("previewMode", 1)
				} else {
					uni.setStorageSync("previewMode", 0)
				}

				//====分享事件上报用    
				if (obj.sharePath) {
					that.shareObj = obj;
				}
			},
			initUserType() {
				uni.setStorageSync("userType", 1)
			},
			/**
			 * @description: 根据场景及参数，跳转至指定页面
			 * @param  scene 扫描参数   options 分享连接参数
			 * @return void
			 */
			navigateToByScene(scene, options) {
				if (scene && scene.length > 0) {
					console.log("scene:", scene)
					api.getSceneInfo({
						interfaceName: scene,
						param: {
							// uuid: scene
						}
					}).then(res => {
						console.log(res)
						if (res.success) {
							var obj = res.data; //JSON.parse(res.data.scene) 
							obj.sharePath = res.data.page
							that.setShareObj(obj)
						}
						that.getUserInfo()
					}).catch(err => {
						that.getUserInfo()
					})
				} else {
					that.setShareObj(options)
					that.getUserInfo()
				}
			},
			showLogin() {
				that.isShowLogin = true
				that.loginType = 0
			},



			onCheckCodeLogin() {
				if (that.checkParam()) {
					var params = {
						verifyCode: that.checkCode,
						account: that.phoneNum,
						tenantCode: that.projectId
					}
					that.phoneLogin(params)
				}
			},
			onAuthLogin() {
        if (!that.isAgreement) {
          uni.showToast({
            icon: "none",
            title: '阅读并同意，《用户协议》和《隐私协议》'
          })
          return false
        }
				if (that.checkProjectId()) {
					console.log("login")
					uni.login({
						provider: 'univerify',
						univerifyStyle: { // 自定义登录框样式
							//参考`univerifyStyle 数据结构`
						},
						success(res) { // 登录成功
							console.log("login success:", res);
							if (res.errMsg == "login:ok") {
								that.appLogin(res.authResult)
							} else {
								uni.showToast({
									icon: "error",
									title: "一键登录失败！"
								})
							}
							uni.closeAuthView()
						},
						fail(res) { // 登录失败
							console.log(res.errCode)
							console.log(res.errMsg)
						}
					})
				}
			},
			onRegister(){
				uni.navigateTo({
					url: "./register"
				})
			},
			appLogin(params) {
				uni.showLoading({
					title: '正在加载...'
				});
				api.loginApp({
					param: {
						openid: params.openid,
						accessToken: params.access_token,
						tenantCode: uni.getStorageSync("projectId"),
					}
				}).then(res => {
					console.log("appLogin:", res)
					if (res.success) {
						uni.setStorageSync('Authorization', res.data)
						that.getUserInfo()
					} else {
						uni.hideLoading();
						uni.showToast({
							duration: 3000,
							icon: "none",
							title: res.message
						})					
					}
				})
			},

			phoneLogin(params) {
				uni.showLoading({
					title: '正在加载...',
					mask: true,
				});

				api.loginPhone({
					param: params
				}).then(res => {
					console.log("appLogin:", res)
					if (res.success) {
						uni.setStorageSync('Authorization', res.data)
						that.getUserInfo()
					} else {
						uni.showToast({
							duration: 3000,
							icon: "none",
							title: res.message
						})
					}
				}).finally(t=>{
					uni.hideLoading();
				})
			},

			getUserInfo() {
				console.log('login......')
				if (!uni.getStorageSync("projectId")) {
					that.showLogin()
					return
				}

				uni.showLoading({
					title: '正在加载...'
				});

				api.getUserInfo().then(res => {
					console.log("getUserInfo:", res)
					if (res.success) {
						that.setUserInfo(res.data)
						that.setLoginStatus(true)
						that.getProjectInfo()
					} else { //if (res.code == 1011004 && !res.success)
						that.showLogin()
					}
				}).finally(t=>{
					uni.hideLoading();
				})

			},

			getProjectInfo() {
				console.log("getProjectInfo")
				api.getProjectInfo({
					param: {
						//===1 预览模式，  0 正常模式
						preview: uni.getStorageSync("previewMode") || 0
					}
				}).then(res => {
					console.log("getProjectInfo", res)
					if (res.success) {
						that.setShopInfo(res.data)
						that.gotoPage()
					}
					uni.hideLoading();
				}).catch(err => {
					console.log("getProjectInfo", err)
				})
			},

			gotoPage() {
				if (that.isExpires) {
					return;
				}

				if (that.shareObj.sharePath.length > 0) {
					var url = decodeURIComponent(that.shareObj.sharePath)
					that.shareObj.sharePath = ''
					uni.navigateTo({
						url: url
					})
				} else {
					uni.redirectTo({
						url: "/pages/shop/tabBar/index"
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.homeContainer {
		width: 100vw;
		height: 100vh;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-image: url(@/static/image/bg_home.jpg);
		display: flex;
		flex-direction: column;
		align-items: center;

		.logoWrapper {
			width: 160rpx;
			height: 160rpx;
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-image: url(@/static/image/logo.png);
			margin-bottom: 20rpx;
			margin-top: 100rpx;
		}

		.nameWrapper {
			height: 37rpx;
			font-family: SourceHanSansCN-Regular;
			font-size: 39rpx;
			font-weight: bold;
			font-stretch: normal;
			line-height: 18rpx;
			letter-spacing: 4rpx;
			color: #191919;
			margin-bottom: 100rpx;
		}

		.itemContainer {
			width: 579rpx;
			height: 94rpx;
			background-color: #e2e4e8;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 40rpx;
			margin-bottom: 24rpx;
			box-sizing: border-box;
			position: relative;
			.left {
				display: flex;
				align-items: center;

				.icon {
					width: 35rpx;
					height: 35rpx;
					margin-right: 30rpx;
				}

				.inputWrapper {
					width: 450rpx;
					height: 40rpx;
				}

			}

			.right {}

			.sendCheckCodeWrapper {
				font-size: 24rpx;
				font-weight: bold;
				color: #fff;
				background-color: #17f;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				border-radius: 10rpx;
				padding: 0 15rpx;
				margin-left: 80rpx;
				position: absolute;
				right: 30rpx;
				top: 17rpx;
			}

			.cutDownWrapper {
				font-size: 24rpx;
				font-weight: bold;
				color: #000000;
				margin-left: 50rpx;
				position: absolute;
				right: 30rpx;
				top: 17rpx;
				line-height: 60rpx;
				.text {
					color: #2aadcf;
					margin-right: 10rpx;
				}
			}

		}

		.checkLoginBtnWrapper {
			width: 579rpx;
			height: 93rpx;
			background-image: linear-gradient(-90deg,
					#2aadcf 0%,
					#33c6d1 100%);
			box-shadow: 0rpx 6rpx 12rpx 0rpx rgba(97, 205, 212, 0.5);
			border-radius: 44rpx;
			color: #e7e6e6;
			font-size: 30rpx;
			font-weight: bold;
			text-align: center;
			line-height: 93rpx;
			margin-bottom: 24rpx;
		}

		.phoneLoginBtnWrapper {
			width: 579rpx;
			height: 93rpx;
			background-color: #d9ebed;
			box-shadow: 0rpx 6rpx 12rpx 0rpx rgba(135, 206, 227, 0.3);
			border-radius: 44rpx;
			color: #2aadcf;
			font-size: 30rpx;
			font-weight: bold;
			text-align: center;
			line-height: 93rpx;
			margin-bottom: 24rpx;
		}

		.bottomContainer {
			position: fixed;
			bottom: 100rpx;
			left: 0;
			width: 750rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			color: #787fff;
			font-size: 24rpx;

			.checkBoxWrapper {
				width: 30rpx;
				height: 30rpx;
				border: solid 2rpx #9da0a3;
				margin-right: 10rpx;
			}
		}
	}

	.expiresWrapper {
		width: 750rpx;
		padding: 0 60rpx;
		text-align: center;
		position: fixed;
		top: 40%;
		font-size: 35rpx;
		font-weight: 600;
		color: #666666;
	}
</style>